//
// Created by chaseaishang on 23-5-16.
//

#include "Gamedata.h"

#include "string.h"
const int quit=4;
const int get_ready=5;//GETREADY
const int un_game_begin=8;//unbegin
const int ask_game_begin=12;//askforbegin
const int in_gaming=14;    // in game
//  0   1234        5           6789        10    11,12,13
// len  x_pos       key_code    delta-T
game_state GameData::unpackData(char *data, int &len,In_gameData *g_data)
{
    if(len==un_game_begin)
    {
        return game_state::UNBEGIN;
    }
    else if(len==quit)
    {
        return game_state::QUIT;
    }
    else if(len==in_gaming)
    {
        if(g_data== nullptr)
        {
            return game_state::FIRSTINGAME;
        }
        int r_len=data[0];
        union change
        {
            float f;
            char fchar[4];
        }ctof;
        for(int i=0;i<4;i++)
        {
            ctof.fchar[i]=data[1+i];
        }
        g_data->x_pos=ctof.f;
        g_data->key_code=data[5];//0 A   1  D    2 Space
        for(int i=0;i<4;i++)
        {
            ctof.fchar[i]=data[6+i];
        }
        g_data->deltaTime=ctof.f;//delta_time


        g_data->Stuck=data[10];
        return game_state::INGAMEING;
    }
    else if(len==get_ready)
    {
        return game_state::GETREADY;
    }
}

void GameData::packData(char *data, int &len, game_state state,In_gameData *g_data)
{
    if(state==game_state::ASKBEGIN)
    {

        char *message="askforbegin";
        strcpy(data+1,message);
        data[ask_game_begin]='\0';
        data[0]=ask_game_begin;
        len=ask_game_begin;
        return;

    }
    else if(state==game_state::INGAMEING)
    {
        int r_len=in_gaming;//14 1 4         8  1
        union change
        {
            float f;
            char fchar[4];
        }ftoc;
        ftoc.f=g_data->x_pos;
        char*message="12345678";
        data[0]=r_len;
        for(int i=0;i<4;i++)
        {
            data[1+i]=ftoc.fchar[i];
        }

        data[5]=g_data->key_code;//0 A   1  D    2 Space
        ftoc.f=g_data->deltaTime;
        for(int i=0;i<4;i++)
        {
            data[6+i]=ftoc.fchar[i];
        }
        data[10]=g_data->Stuck;

        data[r_len]='\0';
        len=data[0];
    }
    else if(state==game_state::GETREADY)
    {//get_ready=5;//GETREADY
        char*message="REDY";
        strcpy(data+1,message);
        data[0]=get_ready;
        len=get_ready;
    }
    else if(state==game_state::QUIT)
    {
        char*message="qqq";
        strcpy(data+1,message);
        data[0]=quit;//4
        len=quit;
    }
}


